<?php
class ti_query
{	
	function __construct($base_sql)
	{
		if(get_class($base_sql) == 'ti_query_builder')
		{
			$base_sql = $base_sql->finalize();
		}
		$this->base_sql = $base_sql;
		$this->final_sql = null;
		$this->data_list = null;
		$this->data      = array();
		$this->style     = false;
		$this->counter   = (-1);
		$this->executed  = false;
	}
	
	function execute($data=null)
	{
		global $ti;
		if(is_null($data))
		{
			$data = $ti->data;
		}
		
		$this->final_sql = $this->base_sql;
		$this->final_sql = ti_util::db_swap($this->final_sql,$data);
		#echo($this->final_sql);
		$ti->log('query: '.$this->final_sql);
		$this->data_list = $ti->config['database.query']($this->final_sql);
		$this->executed  = true;	
	}
	
	function next($data=null)
	{
		global $ti;
		if(!$this->executed)
		{
			$this->execute($data);
		}
		$this->counter++;
		$this->style = (!$this->style);
		return ($this->data = $ti->config['database.fetch_assoc']($this->data_list));
	}
	
	function block($block,$data=null)
	{
		global $ti;
		$html = '';
		while($this->next($data))
		{
			$html .= ti_util::swap($block,$this->data);
		}
		return $html;
	}
	
	function swap_block($position,$block,$data=null)
	{
		global $ti;
		$html = $this->loop_block($block,$data);
		$ti->swap[$position] .= $html;
	}
	
	function num_rows()
	{
		global $ti;
		return $ti->config['database.num_rows']($this->data_list);
	}
	
	function to_js_options($val_col,$text_col,$selected=null)
	{
		$opts = array();
		while($this->next())
		{
			
			$opts[] = '[\''.implode("','",array($this->data[$val_col],$this->data[$text_col],($this->data[$val_col] == $selected))).'\']';
		}
		return '['.implode(',',$opts).']';
	}
}
?>